package scheduler

import (
	"context"
	"fmt"
	"github.com/zhongshaofa/swan-jobs/internal/rpc/proto/scheduler"
	"google.golang.org/grpc"
	"log"
	"net"
)

type Service struct {
	scheduler.UnimplementedServiceServer
}

func (Service) RecordLog(context context.Context, request *scheduler.LogRequest) (*scheduler.Response, error) {
	fmt.Println("RecordLog", request)

	return &scheduler.Response{
		ErrorCode: 0,
		ClientId:   1,
		Message:   1,
	}, nil
}

func (Service) StartTask(context context.Context, request *scheduler.TaskRequest) (*scheduler.TaskResponse, error) {
	return &scheduler.TaskResponse{
		ErrorCode:      0,
		Message:        1,
		ErrorTaskIds:   nil,
		SuccessTaskIds: request.TaskIds,
	}, nil
}

func (Service) ReloadTask(context context.Context, request *scheduler.TaskRequest) (*scheduler.TaskResponse, error) {
	return &scheduler.TaskResponse{
		ErrorCode:      0,
		Message:        1,
		ErrorTaskIds:   nil,
		SuccessTaskIds: request.TaskIds,
	}, nil
}

func (Service) StopTask(context context.Context, request *scheduler.TaskRequest) (*scheduler.TaskResponse, error) {
	return &scheduler.TaskResponse{
		ErrorCode:      0,
		Message:        1,
		ErrorTaskIds:   nil,
		SuccessTaskIds: request.TaskIds,
	}, nil
}

func (Service) OneKeyReloadSupervisor(context context.Context, request *scheduler.TaskRequest) (*scheduler.TaskResponse, error) {
	return &scheduler.TaskResponse{
		ErrorCode:      0,
		Message:        1,
		ErrorTaskIds:   nil,
		SuccessTaskIds: request.TaskIds,
	}, nil
}

func Start(address string) {
	lis, err := net.Listen("tcp", address)
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	s := grpc.NewServer()
	scheduler.RegisterServiceServer(s, &Service{})
	log.Printf("server listening at %v", lis.Addr())
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}
